#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
六度-周期性报告生成器 - 报告转换模块
将Markdown格式的报告模板转换为Word DOC文档，确保宋体字体正确设置
by: 六度科技 04826d.cn
"""

import os
import re
import random
from datetime import datetime, time
try:
    from docx import Document
    from docx.shared import Inches, Pt
    from docx.enum.text import WD_ALIGN_PARAGRAPH
    from docx.oxml.shared import OxmlElement, qn
except ImportError:
    print("需要安装必要的库，请运行以下命令：")
    print("pip install python-docx")
    exit(1)

def set_run_font(run, font_name='宋体', font_size=12):
    """设置run的字体"""
    run.font.name = font_name
    run.font.size = Pt(font_size)
    # 设置东亚字体
    r = run._element
    rPr = r.get_or_add_rPr()
    rFonts = rPr.xpath('.//w:rFonts')[0] if rPr.xpath('.//w:rFonts') else OxmlElement('w:rFonts')
    if not rPr.xpath('.//w:rFonts'):
        rPr.append(rFonts)
    rFonts.set(qn('w:ascii'), font_name)
    rFonts.set(qn('w:eastAsia'), font_name)
    rFonts.set(qn('w:hAnsi'), font_name)

def set_paragraph_font(paragraph, font_name='宋体', font_size=12):
    """设置段落字体"""
    for run in paragraph.runs:
        set_run_font(run, font_name, font_size)

def set_file_timestamp(file_path, report_date_str):
    """设置文件的创建和修改时间为报告日期的工作时间"""
    try:
        # 解析报告日期，支持多种格式
        date_patterns = [
            r'(\d{4})年(\d{1,2})月(\d{1,2})日',  # 2025年01月29日
            r'(\d{4})-(\d{1,2})-(\d{1,2})',      # 2025-01-29
            r'(\d{4}/\d{1,2}/\d{1,2})',          # 2025/01/29
        ]
        
        report_date = None
        for pattern in date_patterns:
            match = re.search(pattern, report_date_str)
            if match:
                if len(match.groups()) == 3:
                    year, month, day = match.groups()
                    report_date = datetime(int(year), int(month), int(day))
                else:
                    # 完整日期字符串
                    try:
                        report_date = datetime.strptime(match.group(1), '%Y/%m/%d')
                    except:
                        continue
                break
        
        if not report_date:
            print(f"⚠️  无法解析报告日期: {report_date_str}，跳过设置文件时间")
            return False
        
        # 生成工作时间段内的随机时间 (9:00-17:00)
        work_start_hour = 9
        work_end_hour = 17
        random_hour = random.randint(work_start_hour, work_end_hour - 1)
        random_minute = random.randint(0, 59)
        random_second = random.randint(0, 59)
        
        # 创建带有随机工作时间的完整时间戳
        file_time = report_date.replace(
            hour=random_hour, 
            minute=random_minute, 
            second=random_second
        )
        
        # 转换为时间戳
        timestamp = file_time.timestamp()
        
        # 设置文件的访问时间和修改时间
        os.utime(file_path, (timestamp, timestamp))
        
        print(f"✅ 已设置文件时间: {file_time.strftime('%Y-%m-%d %H:%M:%S')}")
        return True
        
    except Exception as e:
        print(f"⚠️  设置文件时间失败: {e}")
        return False

def create_table_from_markdown(doc, table_text):
    """从Markdown表格文本创建Word表格"""
    lines = table_text.strip().split('\n')
    if len(lines) < 2:
        return
    
    # 解析表格头
    headers = [cell.strip() for cell in lines[0].split('|')[1:-1]]
    if not headers:
        return
    
    # 跳过分隔行，解析数据行
    data_rows = []
    for line in lines[2:]:
        if line.strip():
            cells = [cell.strip() for cell in line.split('|')[1:-1]]
            if len(cells) == len(headers):
                data_rows.append(cells)
    
    # 创建表格
    table = doc.add_table(rows=1, cols=len(headers))
    table.style = 'Table Grid'
    
    # 设置表头
    hdr_cells = table.rows[0].cells
    for i, header in enumerate(headers):
        hdr_cells[i].text = header
        # 设置表头格式
        for paragraph in hdr_cells[i].paragraphs:
            paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
            for run in paragraph.runs:
                set_run_font(run, '宋体', 12)
                run.bold = True
    
    # 添加数据行
    for row_data in data_rows:
        row_cells = table.add_row().cells
        for i, cell_data in enumerate(row_data):
            if i < len(row_cells):
                row_cells[i].text = cell_data
                # 设置数据行字体
                for paragraph in row_cells[i].paragraphs:
                    for run in paragraph.runs:
                        set_run_font(run, '宋体', 11)

def add_paragraph_with_font(doc, text, font_name='宋体', font_size=12, bold=False, style=None):
    """添加带字体设置的段落"""
    p = doc.add_paragraph()
    if style:
        p.style = style
    
    if '**' in text:
        # 处理包含粗体的文本
        parts = text.split('**')
        for idx, part in enumerate(parts):
            if part:  # 跳过空字符串
                run = p.add_run(part)
                set_run_font(run, font_name, font_size)
                if idx % 2 == 1:  # 奇数索引是粗体部分
                    run.bold = True
                elif bold:
                    run.bold = True
    else:
        # 普通文本
        run = p.add_run(text)
        set_run_font(run, font_name, font_size)
        if bold:
            run.bold = True
    
    return p

def markdown_to_docx(md_file, docx_file):
    """将Markdown文件转换为Word文档"""
    try:
        # 读取Markdown文件
        with open(md_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 创建新的Word文档
        doc = Document()
        
        # 设置页面边距
        sections = doc.sections
        for section in sections:
            section.top_margin = Inches(1)
            section.bottom_margin = Inches(1)
            section.left_margin = Inches(1)
            section.right_margin = Inches(1)
        
        lines = content.split('\n')
        i = 0
        
        while i < len(lines):
            line = lines[i].strip()
            
            # 处理标题
            if line.startswith('#'):
                level = len(line) - len(line.lstrip('#'))
                title_text = line.lstrip('# ').strip()
                
                if level == 1:
                    # 一级标题
                    heading = doc.add_heading(title_text, 1)
                    heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    # 设置标题字体
                    for run in heading.runs:
                        set_run_font(run, '宋体', 16)
                elif level == 2:
                    # 二级标题
                    heading = doc.add_heading(title_text, 2)
                    for run in heading.runs:
                        set_run_font(run, '宋体', 14)
                elif level == 3:
                    # 三级标题
                    heading = doc.add_heading(title_text, 3)
                    for run in heading.runs:
                        set_run_font(run, '宋体', 13)
                else:
                    # 四级及以下标题
                    heading = doc.add_heading(title_text, 4)
                    for run in heading.runs:
                        set_run_font(run, '宋体', 12)
            
            # 处理表格
            elif line.startswith('|'):
                # 收集整个表格
                table_lines = [line]
                j = i + 1
                while j < len(lines) and (lines[j].strip().startswith('|') or lines[j].strip().startswith('|-')):
                    table_lines.append(lines[j].strip())
                    j += 1
                
                table_text = '\n'.join(table_lines)
                create_table_from_markdown(doc, table_text)
                doc.add_paragraph()  # 在表格后添加空行
                i = j - 1
            
            # 处理分隔线
            elif line.startswith('---'):
                # 添加分页符
                doc.add_paragraph('').add_run().add_break()
            
            # 处理普通段落和列表
            elif line:
                if line.startswith('- **') or line.startswith('* **'):
                    # 处理粗体列表项
                    bullet_text = line.lstrip('- *').strip()
                    p = add_paragraph_with_font(doc, bullet_text, '宋体', 12, style='List Bullet')
                
                elif line.startswith('- ') or line.startswith('* '):
                    # 普通列表项
                    bullet_text = line.lstrip('- *').strip()
                    p = add_paragraph_with_font(doc, bullet_text, '宋体', 12, style='List Bullet')
                
                elif line.startswith('**') and line.endswith('**'):
                    # 粗体段落
                    text = line.strip('*')
                    p = add_paragraph_with_font(doc, text, '宋体', 12, bold=True)
                
                else:
                    # 普通段落
                    p = add_paragraph_with_font(doc, line, '宋体', 12)
            
            i += 1
        
        # 保存文档
        doc.save(docx_file)
        print(f"已成功转换: {md_file} -> {docx_file}")
        
        # 尝试从内容中提取报告日期并设置文件时间
        try:
            # 在文档内容中搜索报告日期
            report_date_match = re.search(r'报告日期：.*?(\d{4}年\d{1,2}月\d{1,2}日)', content)
            if report_date_match:
                report_date_str = report_date_match.group(1)
                print(f"🗓️  检测到报告日期: {report_date_str}")
                set_file_timestamp(docx_file, report_date_str)
            else:
                # 尝试其他日期格式
                date_patterns = [
                    r'(\d{4}-\d{1,2}-\d{1,2})',  # 2025-01-29
                    r'(\d{4}/\d{1,2}/\d{1,2})',  # 2025/01/29
                ]
                for pattern in date_patterns:
                    match = re.search(pattern, content)
                    if match:
                        report_date_str = match.group(1)
                        print(f"🗓️  检测到日期: {report_date_str}")
                        set_file_timestamp(docx_file, report_date_str)
                        break
                else:
                    print("ℹ️  未检测到报告日期，使用默认文件时间")
        except Exception as e:
            print(f"⚠️  处理文件时间时出错: {e}")
        
        return True, "转换成功"
        
    except Exception as e:
        error_message = f"转换 '{md_file}' 时发生错误: {e}"
        print(error_message)
        return False, error_message 